﻿/*
* Slickflow 工作流引擎遵循LGPL协议，也可联系作者商业授权并获取技术支持；
* 除此之外的使用则视为不正当使用，请您务必避免由此带来的商业版权纠纷。

The Slickflow Designer project.
Copyright (C) 2014  .NET Workflow Engine Library

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, you can access the official
web page about lgpl: https://www.gnu.org/licenses/lgpl.html
*/

var processlist = (function () {
	function processlist() {
	}

	processlist.pselectedProcessEntity = null;
    processlist.afterCreated = new slick.Event();
	processlist.afterOpened = new slick.Event();

	//#region Process DataGrid
	processlist.getProcessList = function () {
		$('#loading-indicator').show();

        jshelper.ajaxPost('/api/Wf2Xml/GetProcessListSimple', null, function (result) {
            if (result.errors.length === 0) {
				var divProcessGrid = document.querySelector('#myProcessGrid');
				$(divProcessGrid).empty();

				var gridOptions = {
					columnDefs: [
						{ headerName: 'ID', field: 'id', width: 50 },
						{ headerName: '流程GUID', field: 'processGUID', width: 120 },
						{ headerName: '流程名称', field: 'processName', width: 200 },
						{ headerName: '版本', field: 'version', width: 40 },
						{ headerName: '状态', field: 'isUsing', width: 40 },
						{ headerName: '创建日期', field: 'createdTime', width: 120 }
					],
					rowSelection: 'single',
					onSelectionChanged: onSelectionChanged,
					onRowDoubleClicked: onRowDoubleClicked
				};

				new agGrid.Grid(divProcessGrid, gridOptions);
				gridOptions.api.setRowData(result.data);

				$('#loading-indicator').hide();

				function onSelectionChanged() {
					var selectedRows = gridOptions.api.getSelectedRows();
					var selectedProcessID = 0;
					selectedRows.forEach(function (selectedRow, index) {
						processlist.pselectedProcessEntity = selectedRow;
					});
				}

                function onRowDoubleClicked(e, args) {
                    processlist.editProcess();
                }
            }
            else {
                $.msgBox({
                    title: "Designer / Process",
                    content: result.message,
                    type: "error"
                });
            }
		});
	}

	processlist.createProcess = function () {
        processlist.pselectedProcessEntity = null;

	    Ext.net.directRequest({
	        cleanRequest: true,
            url: '/Workflow/process/Create',
	        //extraParams: params,
	        method: "GET",
	        control: this,
	        eventMask: {
	            showMask: true,
	            msg: "正在打开..."
	        }
	    });
	}

	processlist.loadProcess = function () {
		//var entity = processlist.pselectedProcessEntity;
		//if (entity !== null) {
		//	$("#txtProcessGUID").val(entity.processGUID);
		//	$("#txtProcessName").val(entity.processName);
		//	$("#txtVersion").val(entity.version);
		//	$("#ddlIsUsing").val(entity.isUsing);
		//	$("#txtDescription").val(entity.description);
		//} else {
		//	$("#txtProcessGUID").val("");
		//	$("#txtProcessName").val("");
		//	$("#txtVersion").val("1");
		//	$("#ddlIsUsing").val();
		//	$("#txtDescription").val("");
		//}
	}

	processlist.editProcess = function () {
		//var entity = processlist.pselectedProcessEntity;
		//if (entity == null) {
		//	$.msgBox({
		//		title: "Designer / Process",
		//		content: "请先选择流程记录！",
		//		type: "alert"
		//	});
		//	return false;
		//}

		//BootstrapDialog.show({
		//	title: '流程编辑',
  //          message: $('<div></div>').load('/Workflow/process/edit2'),
  //          draggable: true
		//});
    }

	processlist.saveProcess = function () {
		//if ($("#txtProcessName").val() == ""
		//	|| $("#txtVersion").val() == "") {
		//			$.msgBox({
		//				title: "Designer / Process",
		//				content: "请输入流程基本信息！",
		//				type: "alert"
		//			});
		//			return false;
		//		}

  //      var entity = {
		//	"ProcessGUID": $("#txtProcessGUID").val(),
		//	"ProcessName": $("#txtProcessName").val(),
		//	"Version": $("#txtVersion").val(),
		//	"IsUsing": $("#ddlIsUsing").val(),
		//	"Description": $("#txtDescription").val()
		//};

		//if (processlist.pselectedProcessEntity === null) {
		//	processapi.create(entity, function (result) {
		//		if (result.errors.length == 0) {
  //                  processlist.pselectedProcessEntity = result.data;
  //                  //render process into graph canvas
		//			if (processlist.afterCreated) {
		//				slick.trigger(processlist.afterCreated, {
  //                          "ProcessEntity": result.data
  //                      });
		//			}
		//		}
		//	});
		//}
		//else
		//	processapi.update(entity);
	}

	processlist.deleteProcess = function () {
		//$.msgBox({
		//	title: "Are You Sure",
		//	content: "确实要删除流程定义记录吗? ",
		//	type: "confirm",
		//	buttons: [{ value: "Yes" }, { value: "Cancel" }],
		//	success: function (result) {
		//		if (result == "Yes") {
		//			var entity = {
		//				"ProcessGUID": processlist.pselectedProcessEntity.processGUID,
		//				"Version": processlist.pselectedProcessEntity.version
		//			};
		//			processapi.delete(entity);
		//			return;
		//		}
		//	}
		//});
	}

	processlist.sure = function () {
		//render process into graph canvas
		if (processlist.pselectedProcessEntity !== null) {
            onDiagramOpen(processlist.pselectedProcessEntity);
		}
    }

    //render process into graph canvas
    function onDiagramOpen(processEntity) {
        if (processlist.afterOpened) {
            slick.trigger(processlist.afterOpened, {
                "ProcessEntity": processEntity
            });
        }
    }

    //open a diagram
    processlist.openProcessDiagram = function (processID) {
        var query = {
            "ID": processID
        };

        processapi.queryProcessFileByID(query, function (result) {
            if (result.errors.length === 0) {
                if (processlist.afterOpened) {
                    slick.trigger(processlist.afterOpened, {
                        "ProcessEntity": result.data
                    });
                }
            } else {
                  Ext.create("Ext.window.Window", {
                    title: "Designer / Process",
                    width: 500,
                    height: 300,
                    layout: "fit",
                    autoShow: true,
                    html: "流程定义记录读取失败！错误：" + result.message
                });
            }
        });
	}

	return processlist;
})()

//process api
var processapi = (function () {
	function processapi() {
	}

	processapi.create = function (entity, callback) {
		//jshelper.ajaxPost('/api/Wf2Xml/CreateProcess',
  //          JSON.stringify(entity),
  //          function (result) {
  //          	if (result.errors.length == 0) {
  //          		$.msgBox({
  //          			title: "Designer / Process",
  //          			content: "新创建流程记录成功保存！",
  //          			type: "info"
  //          		});
  //          	} else {
  //          		$.msgBox({
  //          			title: "Designer / Process",
  //          			content: result.message,
  //          			type: "error",
  //          			buttons: [{ value: "Ok" }],
  //          		});
  //          	}

  //          	//execute render in processlist
  //          	callback(result);
  //          });
	}

	processapi.update = function (entity) {
		//jshelper.ajaxPost('/api/Wf2Xml/UpdateProcess',
  //          JSON.stringify(entity),
  //          function (result) {
  //          	if (result.errors.length == 0) {
  //          		$.msgBox({
  //          			title: "Designer / Process",
  //          			content: "流程记录成功保存！",
  //          			type: "info"
  //          		});
  //          	} else {
  //          		$.msgBox({
  //          			title: "Ooops",
  //          			content: result.message,
  //          			type: "error",
  //          			buttons: [{ value: "Ok" }],
  //          		});
  //          	}
  //          });
	}

	processapi.delete = function (entity) {
		//delete the selected row
		//jshelper.ajaxPost('/api/Wf2Xml/DeleteProcess',
  //          JSON.stringify(entity),
  //          function (result) {
  //          	if (result.errors.length == 0) {
  //          		$.msgBox({
  //          			title: "Designer / Process",
  //          			content: "流程记录已经删除！",
  //          			type: "info"
  //          		});

  //          		//refresh
  //          		processlist.getProcessList();
  //          	} else {
  //          		$.msgBox({
  //          			title: "Ooops",
  //          			content: result.message,
  //          			type: "error",
  //          			buttons: [{ value: "Ok" }],
  //          		});
  //          	}
  //          });
	}

    processapi.queryProcessFile = function (query, callback) {
        jshelper.ajaxGet('/api/Wf2Xml/QueryProcessFile',
            query,
            function (result) {
            	callback(result);
            }
        );
    }

    processapi.queryProcessFileByID = function (query, callback) {
        jshelper.ajaxGet('/api/Wf2Xml/QueryProcessFileByID',
            query,
            function (result) {
                callback(result);
            }
        );
    }

	processapi.saveProcessFile = function (entity) {
		jshelper.ajaxPost('/api/Wf2Xml/SaveProcessFile', JSON.stringify(entity), function (result) {
			if (result.status == "1") {
			    Tip("Designer / Index", "流程XML内容保存成功！");
			} else {
                Tip("Designer / Index", "流程XML内容保存失败！错误信息：" + result.message);
			}
		});
    }

	return processapi;
})()